package com.leinbo.onedoc.config

import com.kotoframework.function.select.select
import com.leinbo.onedoc.kpojo.Config
import com.leinbo.onedoc.utils.CommonUtil.globalConfig
import com.leinbo.onedoc.utils.Register.registerAll
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.*
import org.springframework.web.util.UrlPathHelper
import java.nio.charset.StandardCharsets
import javax.annotation.PostConstruct

/**
 * Created by sundaiyue on 2022/3/30 09:43
 */
@Configuration
class WebMvcConfiguration : WebMvcConfigurer {
    @Value("\${path.resourceHandler.download}")
    private val downloadResourceHandler: String? = null

    /**
     * 解决跨域问题
     * 配置的大意就是允许所有请求跨域访问
     *
     * @param registry
     */
    override fun addCorsMappings(registry: CorsRegistry) {
        registry.addMapping("/**")
            .allowedHeaders(
                "Content-Type",
                "X-Requested-With",
                "accept,Origin",
                "Access-Control-Request-Method",
                "Access-Control-Request-Headers",
                "token",
                "version"
            )
            .allowedOriginPatterns("*")
            .allowCredentials(true)
            .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
            .maxAge(3600)
    }

    /**
     * 配置静态资源映射
     *
     * @param registry
     */
    override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
        globalConfig = select(Config(1)).by(Config::id).queryForObjectOrNull() ?: Config()
        //就是说 url 中出现 resourceHandler 匹配时，则映射到 location 中去,location 相当于虚拟路径
        //映射本地文件时，开头必须是 file: 开头，表示协议
        val handlers = mapOf(
            downloadResourceHandler to globalConfig.downloadPath //需要以 / 结尾
        )
        for ((key, value) in handlers) {
            registry.addResourceHandler(key).addResourceLocations("file:$value")
        }
    }

    override fun configurePathMatch(configurer: PathMatchConfigurer) {
        val urlPathHelper = UrlPathHelper()
        urlPathHelper.isUrlDecode = false
        urlPathHelper.setDefaultEncoding(StandardCharsets.UTF_8.name())
        configurer.setUrlPathHelper(urlPathHelper)
    }

    @PostConstruct
    fun init() {
        registerAll()
    }
}
